--[[
    @Author       : GGELUA
    @Date         : 2021-03-29 15:47:00
    @LastEditTime : 2021-04-01 16:06:34
--]]
local print = require("cprint")
local isdebug = require("ggelua").isdebug
local lcolor = {
    info = '\x1b[47;30minfo\x1b[0m',
    warn = '\x1b[43;30mwarn\x1b[0m',
    error = '\x1b[41;30merror\x1b[0m'
}

local GGE日志 = class('GGE日志')

function GGE日志:GGE日志(file,logger)
    self.logger = logger or "GGELUA"
    self.SQL = require("LIB.SQLITE3")(file or "log.db3")

    local r = self.SQL:取行数("select count(*) from sqlite_master where name='log';")
    if r==0 then
        self.SQL:执行[[
            CREATE TABLE "log" (
                "date" integer NOT NULL,
                "logger" TEXT,
                "level" integer NOT NULL,
                "message" TEXT NOT NULL,
                "exception" TEXT
              );
        ]]
    end
end

function GGE日志:log(level,msg,...)
    if select("#", ...)>0 then
        msg = msg:format(...)
    end
    local time = os.time()
    print(string.format( "[%s][%s] %s",
        os.date("%X",time),
        lcolor[level] or level,
        tostring(msg))
    )
    local r = self.SQL:执行("insert into log(date,logger,level,message) values('%d','%s','%s','%s')",
        time,
        self.logger,
        level,
        msg
    )
end

function GGE日志:info(msg,...)
    self:log('info',msg,...)
end

function GGE日志:warn(msg,...)
    self:log('warn',msg,...)
end

function GGE日志:error(msg,...)
    self:log('error',msg,...)
end

function GGE日志:debug(msg,...)
    if isdebug then
        self:log('debug',msg,...)
    end
end
return GGE日志
